<?php

namespace app\admin\common\controller;

use app\admin\framework\api\Permission;
use app\common\model\Order;
use app\common\model\OrderLogisticsLog;
use app\common\model\OrderTrip;
use app\common\service\OrderService;
use app\common\service\UserService;
use app\common\utils\Excel;
use think\facade\Db;

#[Permission('中转订单', 'Order', 2)]
class TransferController
{
    private $deptId = 0;
    
    public function __construct()
    {
        $this->deptId = UserService::getValue('dept_id');
    }
    
    
    #[Permission('参数')]
    public function option()
    {
        return apiSuccess(data: [
            'status' => OrderTrip::TRANSFER_START_STATUS
        ]);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $keyword = request()->get('keyword', '');
        $status = request()->get('status');
        $list = OrderService::getLists('dept.list',[
            'status'    =>  $status,
            'keyword'   =>  $keyword,
            'identity'  =>  'center'
        ]);
        return apiSuccess(data: ['list' => $list->items(), 'total' => $list->total()]);
    }
    
    #[Permission('物流追踪')]
    public function logistics()
    {
        $id = request()->get('id', 0);
        return apiSuccess(data: OrderService::getLogistics($id));
    }
    
    #[Permission('验车报告')]
    public function takephone()
    {
        $id = request()->get('id', 0);
        return apiSuccess(data: OrderService::getTrip($id)->photos);
    }
    
    #[Permission('编辑')]
    public function update()
    {
        $id = request()->post('id', 0);
        $status = request()->post('status', 0);
        $data = request()->post('data');
        OrderService::update($id, $status, $data);
        return apiSuccess('编辑成功');
    }
    
     #[Permission('excel')]
    public function excel()
    { 
        $keyword = request()->get('keyword', ''); 
        $status = request()->get('status');
        $list = OrderService::getLists('dept.list', [ 
            'keyword' => $keyword,
            'status' => $status,
            'identity' => 'center'
        ],true);
        
        $arr = [];
        foreach ($list as $key => $value){ 
            $boardItem = Db::name('order_board_item')->where('order_id',$value->id)->find(); 
            if(!empty($boardItem)){
                $allcost = Db::name('order_board_item')->where('order_id', $value->id)->sum('total_price');
                $arr[] = [
                    $value->create_time,
                    $value->address,
                    $value->end_address,
                    $value->car_brand,1,
                    $value->pay_type_text,
                    $value->shipper_name,
                    $value->shipper_mobile,
                    $boardItem['landing_price'],
                    $boardItem['transfer_price'],
                    $boardItem['freight_price'],
                    $value->car_shelf_num,
                    bcsub(floatval($value->total_price),$allcost,2)
                ];
            } 
        } 
        
        $filePath = Excel::import('', [
            '日期', '起运地', '到达地', '车辆名称', '台数', '到付', '收车人', '电话', '接车费', '中转费', '付司机运费', '车架号', '单台毛利润'
        ], $arr); 
        return apiSuccess(data: ['url'=>getImageUrl($filePath)]);
    }
    
    #[Permission('excelAll')]
    public function excelAll()
    { 
        $keyword = request()->get('keyword', '');
        $timeBetween = request()->get('timeBetween', []);
        $orderStatus = request()->get('orderStatus', '');
        $start_dept_id = request()->get('start_dept_id', '');
        $end_dept_id = request()->get('end_dept_id', '');
        $dept_id = request()->get('dept_id');
        $carStatus = request()->get('carStatus', '');
        $timeType = request()->get('timeType', 1);

        $list = OrderService::getLists('adminAll', [ 
            'keyword' => $keyword,
            'timeBetween' => $timeBetween,
            'orderStatus' => $orderStatus,
            'start_dept_id' => $start_dept_id,
            'end_dept_id' => $end_dept_id,
            'dept_id' => $dept_id,
            'carStatus' => $carStatus,
            'timeType' => $timeType,
        ],true);
        // $field = 'ot.*,o.total_price,o.order_sn,o.shipper_name,o.shipper_mobile,o.accept_name,o.accept_mobile,o.car_brand,o.address,o.nickname,o.end_address,o.car_shelf_num,o.pay_type,o.total_price3,o.car_worth,o.insure_price';
        // $where[] = ['order_sn|accept_mobile|shipper_mobile','like','%'.$keyword.'%'];
        // $userInfo = UserService::get();
        // $roles = UserService::getRoleIds($userInfo['id']);
        // if(!in_array(1,$roles)){
        //     $where[] = ['ot.dept_id', '=', $userInfo['dept_id']];
        // }
        // $timeBetween = request()->get('timeBetween',[]);
        // if(!empty($timeBetween)){
        //     $where[] = ['o.create_time','between',$timeBetween];
        // }
        // $list = OrderTrip::alias('ot')->join('order o','o.id = ot.order_id','left')->where($where)->field($field)->order('id desc,order_id desc')->select()->each(function($item){
        // });
        
        $arr = [];  
        $order = new Order();
        foreach ($list->toArray() as $key => $value){ 
            $oneData = [];
            $oneData[] = substr($value['create_time'],0,10);
            $oneData[] = $value['order_sn'];
            $oneData[] = 1;
            //2024-04-03 增加一个 建单人信息
            $deptInfo = Db::name('dept')->where('id',$value['dept_id'])->find();
            $oneData[] = $deptInfo['name'].' - '.$value['nickname'];
//            if(strpos($value['address'],'省') && strpos($value['address'],'市')){
//                $oneData[] = explode('省',explode('市',$value['address'])[0])[1];
//            }else{
//                $oneData[] = $value['address'];
//            }
            $oneData[] = $value['address'];
//            if(strpos($value['end_address'],'省') && strpos($value['end_address'],'市')){
//                $oneData[] = explode('省',explode('市',$value['end_address'])[0])[1];
//            }else{
//                $oneData[] = $value['end_address'];
//            }
            $oneData[] = $value['end_address'];
            $oneData[] = $value['car_brand'];
            $oneData[] = $value['car_shelf_num'];
            switch($value['pay_type']){
                case 1:
                    $oneData[]=$value['total_price'];
                    $oneData[]=0;
                    break;
                case 2:
                    $oneData[]=0;
                    $oneData[]=$value['total_price'];
                    break;
                case 3:
                    $oneData[]=0;
                    $oneData[]=0;
                    break;
            }
//            $oneData[] = $value['total_price3'];
            $oneData[] = $value['ot_status_text'];
            $oneData[] = $value['shipper_name'];
            $oneData[] = $value['shipper_mobile'];
            $oneData[] = $value['accept_name'];
            $oneData[] = $value['accept_mobile'];
            $oneData[] = $value['car_worth']."万";
            $oneData[] = $value['insure_price'];
            //中转数据
            // $nexts = json_decode($value['nexts'],true);
            
            $allPrice = 0;
            //1.先配置始发站
            $oneData[] = $value['total_price'];  //始发站运费
            $field = "obi.*,ob.driver_name,ob.driver_mobile,ob.license,ob.company_name,ob.company_mobile,ob.company_nickname";
            $stattionInfo = Db::name('order_board_item')
            ->alias('obi')
            ->join('order_board ob', 'ob.id = obi.board_id', 'LEFT')
            ->where('obi.order_id', $value['id'])
            ->where('obi.dept_id', $value['dept_id'])
            ->field($field)->find();
            //始发站车辆信息
            // if(!empty($stattionInfo)){
            //     $oneData[] = $stattionInfo['driver_name'].$stattionInfo['driver_mobile'];  
            // }else{
            //     $oneData[] = "";
            // }
            
            $driver_name = [];
            $driver_mobile = [];
            $license = [];
            
            $allPrice += bcadd($allPrice,floatval($value['total_price']),2);
            
            $nexts = Db::name('order_board_item')
                    ->alias('obi')
                    ->join('order_board ob', 'ob.id = obi.board_id', 'LEFT')
                    ->where('obi.order_id', $value['id'])
                    ->field($field)->limit(3)->select();
                    
            $allcost = Db::name('order_board_item')->where('order_id', $value['id'])->sum('total_price');

            if ($value["trip_status"] == 4 && count($nexts) > 0) {
                $nums = count($nexts);
                $oneData[] = ($nums - 1) * 30;
                $oneData[] = 20;
            } else {
                $oneData[] = 0;
                $oneData[] = 0;
            }
            
            //2.中转站信息
            foreach ($nexts as $k=>$v){
                $depts_name = Db::name('dept')->where('id',$v['next_dept_id'])->value('name');
                $detail = "运费:".$v['freight_price']."|加油费:".$v['fuel_price']."|装卸费:".$v['handling_price']."|叉车费:".$v['forklift_price']."|其他费:".$v['other_price']."|中转费:".$v['transfer_price']."|落站费:".$v['landing_price'];
                if(!empty($depts_name)){
                    $oneData[] = $depts_name;
                    $oneData[] = $detail;
                    $oneData[] = $v['total_price'];
                    // $oneData[] = $stattionInfo['driver_name'].$stattionInfo['driver_mobile'];
                    $driver_name[]      = $v['driver_name']?$v['driver_name']:$v['company_name'];
                    $driver_mobile[]    = $v['driver_mobile']?$v['driver_mobile']:$v['company_mobile'];
                    $license[]          = $v['license']?$v['license']:$v['company_nickname'];
                }else{
                    $oneData[] = '';
                    $oneData[] = $detail;
                    $oneData[] = $v['total_price'];
                }
                // $allPrice = bcadd($allPrice,floatval($v['total_price']),2);
            }

            if(count($nexts) < 3){
                for($i=0;$i<3-count($nexts);$i++){
                    $oneData[] = ""; 
                    $oneData[] = ""; 
                    $oneData[] = "";
                }
            }
            // $oneData[] = str_replace('类型','',$order->getShipperTypeTextAttr("1",$value));
            // $oneData[] = $value['commission']; //返款金额
            // $allcost = bcadd($allPrice,floatval($value['commission']),2);//总成本
            // $oneData[] = $value['commission_data']; //返款对象信息
            // $oneData[] = $value['additional_remark']; //额外费用明细
            // $oneData[] = $value['additional_cost']; //额外费用金额
            // $allcost = bcadd($allcost,$value['additional_cost'],2);//总成本
            $oneData[] = $allcost;//全程运费
//            $oneData[] = bcsub(floatval($value['total_price']),$allcost,2);//单台毛利
            $oneData[] = bcsub(bcsub(floatval($value['total_price']),$allcost,2), $value['insure_price'], 2);//单台毛利
            $oneData[] = !empty($driver_name)?implode(',', $driver_name):'';
            $oneData[] = !empty($driver_mobile)?implode(',', $driver_mobile):'';
            $oneData[] = !empty($license)?implode(',', $license):'';
            $oneData[] = $value["eta"];
            $oneData[] = "";
            // print_r($oneData);exit;
            $arr[] = $oneData;
        }
        // print_r($arr);exit;
        $filePath = Excel::import('', [
            "日期",
            "运单号",
            "台数",
            "创建订单人",
            "起运地",
            "到达地",
            "车型品牌",
            "车辆识别码",
            "到付",
            "现付",
            "订单状态", // +
            "发车人",
            "电话",
            "收车人",
            "电话",
            "车值",
            "保险费(元)",
            "运输费总额",
            "付中转费30元/次",
            "付落地费20元/次",
            // "始发运营商姓名电话",
            "中转地1",
            "中转地1-费用明细",
            "中转地1-总费用（元）",
            // "中转地1运营商姓名电话",
            "中转地2",
            "中转地2-费用明细",
            "中转地2-总费用（元）",
            // "中转地2运营商姓名电话",
            "中转地3",
            "中转地3-费用明细",
            "中转地3-总费用（元）",
            // "中转地3运营商姓名话",
            "全程司机运输总费用（元）", // +
            // "客户类型",
            // "返款金额",
            // "返款姓名电话",
            // "额外费用明细",
            // "额外费用明细金额",
            // "全程运输运费（元）",
            "单台毛利润",
            "司机姓名", // +
            "司机电话", // +
            "司机车牌号", // +
            "预计到达时间", // +
            "备注"
        ], $arr);
        return apiSuccess(data: ['url'=>getImageUrl($filePath)]);
    }
    
}